<?php
/**
 *
 * @since 30.12.2011
 * @author Akulov Denis
 */
class K_Logger_Item {

    /**
     * @var string
     */
    private $_name = '';


    /**
     * @var integer
     */
    private $_date = 0;


    public function __construct ($name, $date) {
        $this->_setName($name);
        $this->_setDate($date);
    }


    /**
     *
     * @return string
     */
    public function getName () {
        return $this->_name;
    }


    /**
     *
     * @param $name
     */
    private function _setName ($name) {
        $this->_name = $name;
    }


    /**
     *
     * @return integer
     */
    public function getDate () {
        return $this->_date;
    }


    /**
     *
     * @param $date
     */
    private function _setDate ($date) {
        $this->_date = $date;
    }


    private function _getLogFile () {
        if (!is_dir(K_Logger::PATH_TO_LOGS.$this->getName())) {
            mkdir(K_Logger::PATH_TO_LOGS.$this->getName(), 0644, true);
        }

        return K_Logger::PATH_TO_LOGS.$this->getName().date('/Y_m_d', $this->getDate()).'.log';
    }


    /**
     *
     * @param string $message
     * @param array $data
     */
    public function addEntry ($message, array $data = array(), $isWithTime = true) {
        $handle = fopen($this->_getLogFile(), 'a');

        if (!$handle) {
            return false;
        }

        if(!is_writeable($this->_getLogFile())) {
            return false;
        }

        if (!flock($handle, LOCK_EX)) {
            return false;
        }

        fwrite($handle, ($isWithTime ? date('H:i:s;') : '').$message.';'.$this->_implode($data)."\n");

        flock($handle, LOCK_UN);
        fclose($handle);
    }


    private function _implode (array $data) {
        if(empty($data)) {
            return '';
        }

        return print_r($data, true);
    }


    public function addStartEntry () {
        $this->addEntry('BEGIN', array(), false);
    }


    public function addEndEntry () {
        $this->addEntry('END', array(), false);
    }


    public function addErrorEntry (Exception $e) {
        $this->addEntry('EXCEPTION BEGIN');
        $this->addEntry("EXCEPTION MESSAGE:\n". $e->getMessage());
        $this->addEntry("EXCEPTION TRACE:\n".$e->getTraceAsString());
        $this->addEntry('EXCEPTION END');
    }

}